import time

from rest_framework import serializers, exceptions

from user_app import models
from user_app.models import User
from article_app.models import Article
from utils.regexp_rule import EMAIL, PASSWORD, NICK_NAME


class UserSimpleSerializer(serializers.ModelSerializer):

    use_time = serializers.SerializerMethodField()
    article_no = serializers.SerializerMethodField()
    fans_no = serializers.SerializerMethodField()
    agree_no = serializers.SerializerMethodField()

    class Meta:
        model = User
        fields = ('nick_name', 'email', 'info', 'avatar', 'use_time', 'fans_no', 'article_no', 'agree_no', 'level')


    def get_use_time(self, obj):
        return (time.time() - obj.register_time) // 86400

    def get_article_no(self, obj):
        return Article.objects.filter(u_id=obj.id, is_delete=0).count()
    
    def get_fans_no(self, obj):
        return 0
    
    def get_agree_no(self, obj):
        return 0

class UserDetailSerializer(serializers.ModelSerializer):
    password = serializers.CharField(write_only=True)

    class Meta:
        model = User
        exclude = ('id',)

    def validate_email(self, value):
        """ 验证邮件是否合法及存在"""
        email = self.initial_data.get('email', '')
        if not EMAIL.search(email):
            raise exceptions.ValidationError(f'邮箱格式不正确 {email}')
        exists = models.User.objects.filter(email=email, is_delete=0).exists()
        if exists:
            raise exceptions.ValidationError(f'该邮箱已被注册 {email}')
        return value

    def validate_nick_name(self, value):
        """ 验证昵称是否合法"""
        nick_name = self.initial_data.get('nick_name', '')
        if not NICK_NAME.search(nick_name):
            raise exceptions.ValidationError(f'昵称格式不正确 {nick_name}')
        return value

    def validate_password(self, value):
        """ 验证昵称是否合法"""
        password = self.initial_data.get('password', '')
        if not PASSWORD.search(password):
            raise exceptions.ValidationError(f'密码格式不正确 {password}')
        return value


class UserLoginSerializer(serializers.Serializer):

    email = serializers.CharField()
    password = serializers.CharField(write_only=True)

    def validate_email(self, value):
        """ 验证邮件是否合法及存在"""
        email = self.initial_data.get('email', '')
        if not EMAIL.search(email):
            raise exceptions.ValidationError(f'邮箱格式不正确 {email}', code=3001)
        return value

    def validate_password(self, value):
        """ 验证昵称是否合法"""
        password = self.initial_data.get('password', '')
        if not PASSWORD.search(password):
            raise exceptions.ValidationError(detail=f'密码格式不正确 {password}', code=3001)
        return value

